package cn.hua.trip.base.service.impl;

import cn.hua.trip.base.domain.Travel;
import cn.hua.trip.base.domain.TravelContent;
import cn.hua.trip.base.mapper.TravelContentMapper;
import cn.hua.trip.base.mapper.TravelMapper;
import cn.hua.trip.base.query.TravelCommendQueryObject;
import cn.hua.trip.base.query.TravelQueryObject;
import cn.hua.trip.base.service.ITravelService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class TravelServiceImpl implements ITravelService{
    @Autowired
    private TravelMapper travelMapper;
    @Autowired
    private TravelContentMapper travelContentMapper;

    @Override
    public PageInfo<Travel> queryForList(TravelQueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize(),qo.getOrderBy());
        List<Travel> list = travelMapper.queryForList(qo);
        return new PageInfo<Travel>(list);
    }


    //得到内容的操作
    @Override
    public TravelContent getContentById(Long travelId) {
        return travelContentMapper.selectByPrimaryKey(travelId);
    }

    //改变状态的操作
    @Override
    public void changeState(Travel travel) {
        travelMapper.changeState(travel);
    }

    //更新游记操作
    @Override
    public void update(Travel travel) {
        //最近更新的时间
        travel.setLastUpdateTime(new Date());
        //更新数据库的操作
        travelMapper.updateByPrimaryKey(travel);
        //更新内容
        TravelContent tc = travel.getTravelContent();
        //设置两者的id值相同
        tc.setId(travel.getId());
        //更新数据库中的内容
        travelContentMapper.updateByPrimaryKey(tc);
    }

    //获得单个的游记
    @Override
    public Travel get(Long id) {
        //先查出游记
        Travel travel = travelMapper.selectByPrimaryKey(id);
        //再查出游记的内容
        TravelContent tc = travelContentMapper.selectByPrimaryKey(id);
        //将内容设置进游记里面
        travel.setTravelContent(tc);
        return travel;
    }

    //保存游记操作
    @Override
    public void save(Travel travel) {
        //设置最后更新时间
        travel.setLastUpdateTime(new Date());
        //设置创建时间
        travel.setCreateTime(new Date());
        //保存游记进数据库
        travelMapper.insert(travel);
        //得到内容对象
        TravelContent tc = travel.getTravelContent();
        //给内容对象同步主键
        tc.setId(travel.getId());
        //保存内容进数据库
        travelContentMapper.insert(tc);
    }

}
